import { useState, useEffect } from 'react';
import { Form, message } from 'antd';
import { get, post, put, del } from '@/utils/request';

export interface MenuTreeItem {
  id: number;
  name: string;
  parent_id: number | null;
  type: string;
  order_num: number;
  children?: MenuTreeItem[];
}

export function useMenuManagement() {
  const [menus, setMenus] = useState<MenuTreeItem[]>([]);
  const [loading, setLoading] = useState(false);
  const [modalVisible, setModalVisible] = useState(false);
  const [editingMenu, setEditingMenu] = useState<MenuTreeItem | null>(null);
  const [form] = Form.useForm();
  const [searchForm] = Form.useForm();
  const [searchParams, setSearchParams] = useState({});

  // 获取菜单树
  const fetchMenus = async () => {
    setLoading(true);
    try {
      const res = await get('/menus');
      setMenus(res || []);
    } catch (error) {
      message.error('获取菜单树失败');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchMenus();
  }, []);

  // 查询（仅支持名称模糊搜索）
  const handleQuery = async (values: any) => {
    setLoading(true);
    try {
      const res = await get('/menus', values);
      setMenus(res || []);
    } catch {
      message.error('查询失败');
    } finally {
      setLoading(false);
    }
  };

  // 重置
  const handleReset = async () => {
    searchForm.resetFields();
    fetchMenus();
  };

  // 新建/编辑菜单
  const handleSubmit = async (values: any) => {
    try {
      if (editingMenu) {
        await put(`/menus/${editingMenu.id}`, {
          name: values.name,
          parent_id: values.parent_id || null,
          type: values.type,
          order_num: values.order_num,
        });
        message.success('菜单更新成功');
      } else {
        await post('/menus', {
          name: values.name,
          parent_id: values.parent_id || null,
          type: values.type,
          order_num: values.order_num,
        });
        message.success('菜单创建成功');
      }
      setModalVisible(false);
      form.resetFields();
      setEditingMenu(null);
      fetchMenus();
    } catch {
      message.error('操作失败');
    }
  };

  // 删除菜单
  const handleDelete = async (id: number) => {
    try {
      await del(`/menus/${id}`);
      message.success('删除成功');
      fetchMenus();
    } catch {
      message.error('删除失败');
    }
  };

  // 获取父级菜单选项（树结构）
  const buildTreeOptions = (menuList: MenuTreeItem[], excludeId?: number): any[] =>
    menuList
      .filter(menu => menu.id !== excludeId)
      .map(menu => ({
        label: menu.name,
        value: menu.id,
        children: menu.children ? buildTreeOptions(menu.children, excludeId) : undefined,
      }));

  const getParentMenuOptions = () => buildTreeOptions(menus, editingMenu?.id);

  return {
    menus,
    loading,
    modalVisible,
    editingMenu,
    form,
    searchForm,
    setModalVisible,
    setEditingMenu,
    fetchMenus,
    handleSubmit,
    handleDelete,
    handleQuery,
    handleReset,
    getParentMenuOptions,
  };
} 